package main

import (
	"context"
	"io"
	"log"
	"net"
	"os"
)

func main() {
	//代理tcp
	runProxy(context.Background(), ":3309", "172.16.0.2:8554")
}

func runProxy(ctx context.Context, addr, remoteAddr string) error {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
		return err
	}
	defer ln.Close()
	log.Printf("proxy listen on %s, remote addr: %s\n", addr, remoteAddr)
	for {
		if ctx.Err() != nil {
			return ctx.Err()
		}
		//接收连接
		conn, err := ln.Accept()
		if err != nil {
			continue
		}
		// go handleConnection(conn)
		go handleConnection(conn, remoteAddr)
	}
}

func handleConnection(conn io.ReadWriteCloser, remote_addr string) (err error) {
	log.Println("on conn", conn)
	defer func() {
		log.Println("on conn end", conn)
	}()
	// //test
	io.Copy(os.Stdout, conn)
	// return nil

	defer conn.Close()
	remote_conn, err := net.Dial("tcp", remote_addr)
	if err != nil {
		return
	}
	go func() {
		n, err := io.Copy(remote_conn, conn)
		log.Println("tx end", n, err)
	}()
	n, err := io.Copy(conn, remote_conn)
	log.Println("rx end", n, err)
	return
}
